/**  
 * @Title OrderCtrl.java
 * @date 2016年4月26日 下午2:16:30
 * @Copyright (c) 2016, unibroad.com Inc. All rights reserved.
 */
package mt.ctrl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import base.ctrl.BaseController;
import base.ctrl.BaseResult;
import base.jfinal.JsonUtil;
import base.jfinal.anatation.RouteBind;
import base.model.SessionModel;
import base.model.exception.BizHandleException;
import base.util.Common;
import base.util.HttpRequestUtils;
import base.util.PropertiesContent;
import mt.Const;
import mt.business.Cache;
import mt.business.UserVO;
import mt.model.Discount;
import mt.model.Order;
import mt.model.ShopTheme;
import mt.model.TeamUser;
import mt.model.ThemeRate;
import mt.model.enums.DiscountStatusEnum;
import mt.model.enums.OrderStatusEnum;
import mt.model.enums.PriceTypeEnum;
import mt.model.enums.ThemeStatusEnum;
import mt.validator.OrderMerchantQueryValidator;
import pay.biz.PayTypeEnum;

/**
 * @Description 订单处理接口
 * @Class mt.ctrl.OrderCtrl
 * @author suan@unibroad.com
 * @version V1.0
 */
@RouteBind(path = "order")
public class OrderCtrl extends BaseController {

	/**
	 * 商家订单查询接口
	 * 
	 * <pre>
	 * 参数：{orderId:"",code:"",themeId:,teamId:,startDate:"yyyy-MM-dd HH:mm:ss",endDate:"yyyy-MM-dd HH:mm:ss"}
	 * </pre>
	 * 
	 * <pre>
	 * 返回结果参考：
	 * {
	"isSuccess": true,
	"message": "",
	"data": {
	        "pageSize": 10,
	        "pageNumber": 1,
	        "list": [
	            {
	                "orderId": "957787812443143",
	                "teamId": 4,
	                "userId": 10,
	                "themeId": 1,
	                "quantity": 1,
	                "money": 10000,
	                "tradeNo": null,
	                "discountId": null,
	                "status": 0,
	                "memo": null,
	                "createTime": "2016-05-03 21:35:38",
	                "updateTime": null,
	                "themeName": "红衣学姐/虫洞 剧情机关密室1",
	                "shopId": 2,
	                "teamName": "team4",
	                "userName": "suan"
	            }
	        ],
	        "totalRow": 1,
	        "totalPage": 1
	    }
	}
	 * </pre>
	 */
	@Before(OrderMerchantQueryValidator.class)
	public void merchantQuery() {

		final String orderId = this.getPara("orderId", null);

		String userCode = this.getPara("code", null);
		UserVO user = Cache.GetUserVOByCode(userCode);

		final int themeId = this.getParaToInt("themeId", -1);
		final int teamId = this.getParaToInt("teamId", -1);
		final Date startDate = this.getParaToDate("startDate", null);
		final Date endDate = this.getParaToDate("endDate", null);
		final int pageNum = this.getParaToInt("page", 1);
		final int pageSize = this.getParaToInt("pageSize", 10);

		List<Object> params = new ArrayList<Object>();
		StringBuilder querySql = new StringBuilder("select morder.*,theme.themeId,theme.themeName,theme.shopId ");

		StringBuilder sqlExceptSelect = new StringBuilder(
				"from mt_order morder,mt_theme theme where morder.themeId = theme.themeId ");
		if (StringUtils.isNotBlank(orderId)) {
			params.add(orderId);
			sqlExceptSelect.append(" and morder.orderId like ?");
		}

		if (teamId > 0) {
			params.add(teamId);
			sqlExceptSelect.append(" and morder.teamId = ?");
		}

		if (user != null) {
			params.add(user.getUserId());
			sqlExceptSelect.append(" and morder.userId = ?");
		}

		if (themeId > 0) {
			params.add(themeId);
			sqlExceptSelect.append(" and morder.themeId = ?");
		}

		if (startDate != null) {
			sqlExceptSelect.append(" and createTime >= ?");
			params.add(startDate);
		}

		if (endDate != null) {
			sqlExceptSelect.append(" and createTime <= ?");
			params.add(endDate);
		}

		// 订单＋主题
		Page<Record> pageOrderInfos = Db.paginate(pageNum, pageSize, querySql.toString(), sqlExceptSelect.toString(),
				params.toArray());
		if (pageOrderInfos == null || pageOrderInfos.getList() == null || pageOrderInfos.getList().isEmpty()) {
			rendJson(new BaseResult<Page<Record>>(true).setData(pageOrderInfos).toJsonString());
		}

		// 补充队伍及用户数据
		BigDecimal price = null;
		for (Record row : pageOrderInfos.getList()) {
			price = row.getBigDecimal("price");
			row.getColumns().put("displayprice", price != null ? price.divide(new BigDecimal(100)) : 0);
			row.getColumns().putAll(Db.findById("mt_team", "teamId", row.getInt("teamId"), "teamName").getColumns());
			row.getColumns().putAll(Db.findById("mt_user", "userId", row.getInt("userId"), "userName").getColumns());
			OrderStatusEnum orderStatus = OrderStatusEnum.getEnumByCode(row.getInt("status"));
			row.getColumns().put("statusDesc", orderStatus != null ? orderStatus.getDescription() : "");
		}

		renderJson(new BaseResult<Page<Record>>(true).setData(pageOrderInfos).toJsonString());
	}

	/**
	 * 终端用户订单查询
	 * 
	 * <pre>
	 * SELECT morder.orderId,morder.userId,morder.quantity,morder.money,morder.tradeNo,morder.status,morder.createTime,morder.themeId,theme.themeName,theme.category,theme.coverImg,shop.shopId,shop.shopName FROM mt_order morder,mt_theme theme,mt_shop shop WHERE morder.userId = 10  AND theme.themeId = morder.themeId AND theme.shopId = shop.shopId ORDER BY morder.createTime DESC,shop.shopId
	 * </pre>
	 * 
	 * <pre>
	 * 参数：{code:"",startDate:"yyyy-MM-dd HH:mm:ss",endDate:"yyyy-MM-dd HH:mm:ss"}
	 * </pre>
	 * 
	 * <pre>
	 * 结果参数
	 * {
	"isSuccess": true,
	"message": "",
	"data": [{
	            "orderId": "957787812443143",
	            "userId": 10,
	            "quantity": 1,
	            "money": 10000,
	            "tradeNo": null,
	            "status": 0,
	            "createTime": "2016-05-03 21:35:38",
	            "themeName": "红衣学姐/虫洞 剧情机关密室1",
	            "category": 1,
	            "coverImg": "http://p4.xyx.hao123img.com/img/bigNewLogo/20131129_big_b70d8cf5ce.jpg",
	            "shopId": 2,
	            "shopName": "帝都"
	        }]
	}
	 * </pre>
	 */
	public void userQuery() {

		String userCode = this.getPara("code", null);
		UserVO user = Cache.GetUserVOByCode(userCode);
		if (user == null) {
			renderJson(new BaseResult<Object>(false, "操作失败，参数错误！"));
			return;
		}

		final Date startDate = this.getParaToDate("startDate", null);
		final Date endDate = this.getParaToDate("endDate", null);

		List<Object> params = new ArrayList<Object>();
		params.add(user.getUserId());
		StringBuilder querySql = new StringBuilder(
				"select morder.orderId,morder.userId,morder.quantity,morder.money,morder.tradeNo,morder.status,morder.createTime,theme.themeName,theme.category,theme.coverImg,shop.shopId,shop.shopName,theme.price from mt_order morder,mt_theme theme,mt_shop shop");
		querySql.append(" where morder.userId = ? ");

		if (startDate != null) {
			querySql.append(" and morder.createTime >= ?");
			params.add(startDate);
		}

		if (endDate != null) {
			querySql.append(" and morder.createTime <= ?");
			params.add(endDate);
		}

		querySql.append(
				" and theme.themeId = morder.themeId and theme.shopId = shop.shopId order by morder.createTime desc,shop.shopId");

		List<Record> relaOrderExtin = Db.find(querySql.toString(), user.getUserId());
		if (relaOrderExtin != null) {
			for (Record row : relaOrderExtin) {
				BigDecimal price = row.getBigDecimal("price");
				row.getColumns().put("displayprice", price != null ? price.divide(new BigDecimal(100)) : 0);
			}
		}
		if (relaOrderExtin == null || relaOrderExtin.isEmpty()) {
			rendJson(new BaseResult<List<Record>>(true).setData(relaOrderExtin).toJsonString());
		}

		for (Record row : relaOrderExtin) {
			OrderStatusEnum orderStatus = OrderStatusEnum.getEnumByCode(row.getInt("status"));
			row.getColumns().put("statusDesc", orderStatus != null ? orderStatus.getDescription() : "");
		}

		this.renderJson(new BaseResult<List<Record>>(true).setData(relaOrderExtin).toJsonString());
	}

	/**
	 * 用户预下单，信息查询
	 * 
	 * <pre>
	 * {themeId:1,themeName:'逃离火山口原始森林',teamId:1,members:5,maxPlayers:7,themePrice:25000,priceType:1,discountNum:2}
	 * </pre>
	 */
	public void preOrder() {
		try {
			String userCode = this.getPara("userCode", null);
			UserVO user = Cache.GetUserVOByCode(userCode);
			String teamId = this.getPara("teamId", null);
			int themeId = this.getParaToInt("themeId", 0);

			if (user == null || StringUtils.isBlank(teamId) || themeId < 1) {
				log.error("预下单失败,参数错误,user=" + user + ",teamId=" + teamId + ",themeId=" + themeId);
				renderJson(new BaseResult<Object>(false, "操作失败，参数错误！"));
				return;
			}

			ShopTheme theme = ShopTheme.dao.findById(themeId);
			if (theme == null || ThemeStatusEnum.getEnumByCode(theme.getInt("status")) != ThemeStatusEnum.OK) {
				renderJson(new BaseResult<Object>(false, "操作失败，主题已下线！"));
				return;
			}

			List<TeamUser> teamUsers = TeamUser.dao.find("select id from mt_team_user where teamId = ?", teamId);

			Map<String, Object> infoMap = new HashMap<String, Object>();
			infoMap.put("teamId", teamId);

			infoMap.put("themeId", themeId);
			infoMap.put("themeName", theme.get("themeName"));
			infoMap.put("priceType", theme.getInt("priceType"));

			if (PriceTypeEnum.getEnumByCode(theme.getInt("priceType")) == PriceTypeEnum.PER_TICKET) {
				infoMap.put("themePrice", theme.getBigDecimal("price"));
			} else {
				ThemeRate rate = ThemeRate.dao.findFirst(
						"select * from mt_theme_rate where themeId = ? and type = 1 and minPlayer <= ? and maxPlayer >=?",
						themeId, teamUsers.size(), teamUsers.size());
				if (rate == null) {
					renderJson(new BaseResult<Object>(false, "操作失败，主题信息缺失！"));
					return;
				}
				infoMap.put("themePrice", rate.getBigDecimal("price"));
			}
			infoMap.put("displayPrice", ((BigDecimal) infoMap.get("themePrice")).divide(new BigDecimal(100)));

			// 查看当前用户当前主题有哪些多少可用的折扣券
			List<Discount> discounts = Discount.dao
					.find("select discountId from mt_discount where userId = ? and (shopId = ? or shopId is null)  and status = "
							+ DiscountStatusEnum.OK.getCode(), user.getUserId(), theme.getInt("shopId"));
			infoMap.put("discountNum", discounts != null ? discounts.size() : 0);
			renderJson(new BaseResult<Object>(true, "OK", infoMap).toJsonString());
		} catch (Exception e) {
			log.error("预备购票失败，系统异常", e);
			renderJson(new BaseResult<Object>(false, "操作失败，系统异常！").toJsonString());
		}
	}

	/**
	 * 用户提交订单, suan TODO 重复提交问题</br>
	 * {"code":"0112dSuZ0GkKnM1EpSsZ04GSuZ02dSub","teamId":111,"quantity":1,
	 * "money":10000,"discount":1,"bizData":{"themeId":1}}
	 * http://localhost:8070/mitao/svr/order/submit.json?code=
	 * 0112dSuZ0GkKnM1EpSsZ04GSuZ02dSub&teamId=4&quantity=1&money=10000&bizData=
	 * {"themeId":5}
	 * 
	 * @throws BizHandleException
	 */
	@Before({ Tx.class })
	public void submit() throws BizHandleException {

		String userCode = this.getPara("userCode", null);
		UserVO user = Cache.GetUserVOByCode(userCode);

		String teamId = this.getPara("teamId", null);
		int themeId = this.getParaToInt("themeId", 0);
		Float realPayment = getParaToFloat("realPayment", 0F);
		Float needPayment = getParaToFloat("needPayment", 0F);
		int payType = this.getParaToInt("payType", -99);
		int ticketNum = this.getParaToInt("ticketNum", 0);
		int discountId = this.getParaToInt("discountId", 0);
		String themeName = this.getPara("themeName", "");

		if (user == null || StringUtils.isBlank(teamId) || themeId < 1 || needPayment <= 0 || ticketNum < 1
				|| (realPayment < needPayment && discountId < 1) || payType < 0) {
			log.error("订单创建失败,参数错误,user=" + userCode + ",teamId=" + teamId + ",themeId=" + themeId + ",needPayment="
					+ needPayment + ",realPayment=" + realPayment + ",discountId=" + discountId + ",payType="
					+ payType);
			renderJson(new BaseResult<Object>(false, "操作失败，参数错误！"));
			return;
		}

		// ShopTheme theme = ShopTheme.dao.findById(themeId);
		// if (theme == null ||
		// ThemeStatusEnum.getEnumByCode(theme.getInt("status")) !=
		// ThemeStatusEnum.OK) {
		// renderJson(new BaseResult<Object>(false, "操作失败，主题已下线！"));
		// return;
		// }

		// 用了折扣券，则校验是否存在，状态是否OK
		Discount discount = null;
		if (discountId > 0) {
			discount = Discount.dao.findById(discountId);
			if (discount == null || DiscountStatusEnum.OK != DiscountStatusEnum.getEnumByCode(discount.getInt("status"))
					|| discount.getDate("endDate") != null && discount.getDate("endDate").before(new Date())) {
				log.error("订单创建失败,优惠券不可用,discountId=" + discountId);
				renderJson(new BaseResult<Object>(false, "操作失败，优惠券状态异常！"));
				return;
			}
		}
		// 应用了优惠券后的金额核对 suan TOD0

		// 创建订单
		Order order = new Order();
		order.set("orderId", Common.genSeriaNO());
		order.set("teamId", teamId);
		order.set("userId", user.getUserId());
		order.set("quantity", ticketNum);

		// 订单金额,以分为单位
		order.set("money", new BigDecimal(needPayment));
		order.set("payment", new BigDecimal(realPayment));
		order.set("payType", payType);
		order.set("status", OrderStatusEnum.WAIT_PAY.getCode());
		order.set("discountId", discountId);
		order.set("themeId", themeId);

		// 占用券
		if (discount != null) {
			discount.set("status", DiscountStatusEnum.USING.getCode());
			if (realPayment <= 0) {
				// 免单则直接付费完成,作废券
				order.set("status", OrderStatusEnum.PAY_SUCCESS.getCode());
				discount.set("status", DiscountStatusEnum.USED.getCode());
			}
			discount.update();
		}

		order.set("createTime", new Date());

		// 保存订单
		if (!order.save()) {
			renderJson(new BaseResult<Order>(false, "订单创建失败，未知异常！", null).toJsonString());
			return;
		}

		BaseResult<Order> result = new BaseResult<Order>();
		result.setSuccess(true).setData(order);

		if (PayTypeEnum.APAY_MOBILE.getCode() == payType) {
			// 生成支付签名
			alipaySign(order, themeName, themeName);
		} else {
			// 微信预下单
			wxPreOrder(order, themeName, themeName);
		}

		String resultJsonStr = new BaseResult<Order>(true, "OK", order).toJsonString();
		log.info("订单创建成功," + resultJsonStr);
		renderJson(resultJsonStr);
	}

	/**
	 * 微信预下单
	 * 
	 * @param order
	 * @param subject
	 * @param body
	 */
	private void wxPreOrder(Order order, String subject, String body) throws BizHandleException {

		String appId = PropertiesContent.get(Const.WXPAY_MSG_KEY_APP_ID);
		String mch_id = PropertiesContent.get(Const.WXPAY_MSG_KEY_wxpay_mct_id);
		String appKey = PropertiesContent.get(Const.WXPAY_MSG_KEY_wxpay_api_key);

		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("appid", appId);
		paramsMap.put("mch_id", mch_id);
		paramsMap.put("device_info", "WEB");
		paramsMap.put("nonce_str", System.nanoTime() + "" + new Random().nextInt(10));
		paramsMap.put("body", body);
		paramsMap.put("out_trade_no", order.getStr("orderId"));
		paramsMap.put("total_fee", String.valueOf(order.getBigDecimal("payment")));
		paramsMap.put("spbill_create_ip", getRequest().getRemoteHost());
		paramsMap.put("notify_url", PropertiesContent.get(Const.WXPAY_MSG_KEY_notify_url));
		paramsMap.put("trade_type", "APP");
		paramsMap.put("product_id", order.getInt("themeId") + "");

		List<String> sortedKeys = new ArrayList<String>(paramsMap.keySet());
		Collections.sort(sortedKeys);
		StringBuilder sb = new StringBuilder();
		String tmpKey = null;
		StringBuilder xmlParms = new StringBuilder("<xml>");
		for (int i = 0; i < sortedKeys.size(); i++) {
			tmpKey = sortedKeys.get(i);
			sb.append(tmpKey).append("=").append(paramsMap.get(tmpKey));
			xmlParms.append("<").append(tmpKey).append(">").append(paramsMap.get(tmpKey)).append("</").append(tmpKey)
					.append(">");
			if (i < sortedKeys.size() - 1) {
				sb.append("&");
			} else {
				sb.append("&key=").append(appKey);
			}
		}

		// log.info("wxpay preOrder sign info = " + sb.toString());

		String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
		xmlParms.append("<sign>").append(sign).append("</sign></xml>");
		// <xml>
		// <appid>wx2421b1c4370ec43b</appid>
		// <attach>支付测试</attach>
		// <body>JSAPI支付测试</body>
		// <mch_id>10000100</mch_id>
		// <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
		// <notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php</notify_url>
		// <openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid>
		// <out_trade_no>1415659990</out_trade_no>
		// <spbill_create_ip>14.23.150.211</spbill_create_ip>
		// <total_fee>1</total_fee>
		// <trade_type>JSAPI</trade_type>
		// <sign>0CB01533B8C1EF103065174F50BCA001</sign>
		// </xml>
		String params = xmlParms.toString();

		String resp = HttpRequestUtils.doPostSSL(PropertiesContent.get(Const.WXPAY_MSG_KEY_preorder_url), params,
				"application/xml");

		Document resultDoc;
		try {
			resultDoc = DocumentHelper.parseText(resp);
		} catch (DocumentException e) {
			log.error("wxPreOrder failure,resp dom parse exception, resp=" + resp);
			throw new BizHandleException("操作失败,微信支付异常!");
		}
		Element rootElement = resultDoc.getRootElement();
		String resultCode = rootElement.elementTextTrim("return_code");
		String tipMsg = rootElement.elementTextTrim("return_msg");
		// 调用返回码
		if (!StringUtils.equalsIgnoreCase(resultCode, "SUCCESS")) {
			log.error("wxPreOrder failure, returnCode=" + resultCode + ",msg=" + tipMsg);
			throw new BizHandleException("操作失败,微信支付异常!");
		}
		resultCode = rootElement.elementTextTrim("result_code");
		tipMsg = rootElement.elementTextTrim("err_code_des");
		if (!StringUtils.equalsIgnoreCase(resultCode, "SUCCESS")) {
			log.error("wxPreOrder failure, bizCode=" + resultCode + ",msg=" + tipMsg);
			throw new BizHandleException("操作失败,微信支付异常!");
		}

		String prepay_id = rootElement.elementTextTrim("prepay_id");
		sb = new StringBuilder();
		String nonce_str = System.nanoTime() + "" + new Random().nextInt(10);
		String timestamp = System.currentTimeMillis() / 1000 + "";
		// sb.append("appid=").append(appId).append("&nonceStr=").append(nonce_str).append("&package=Sign=WXPay")
		// .append("&partnerId=").append(mch_id).append("&prepayId=").append(prepay_id)
		// .append("&timeStamp=").append(timestamp).append("&key=").append(appKey);
		sb.append("appid=").append(appId).append("&noncestr=").append(nonce_str).append("&package=Sign=WXPay")
				.append("&partnerid=").append(mch_id).append("&prepayid=").append(prepay_id).append("&timestamp=")
				.append(timestamp).append("&key=").append(appKey);
		sign = DigestUtils.md5Hex(sb.toString().getBytes()).toUpperCase();

		// orderId :ret.orderId,
		// partnerId:'******',
		// nonceStr :noncestr,
		// timeStamp:timestamp,
		// package:'Sign=WXPay',
		// sign:signatureInfoT
		JSONObject payParamsJSON = new JSONObject();
		payParamsJSON.put("apiKey", appId);
		payParamsJSON.put("orderId", prepay_id);
		payParamsJSON.put("mchId", mch_id);
		payParamsJSON.put("nonceStr", nonce_str);
		payParamsJSON.put("timeStamp", timestamp);
		payParamsJSON.put("package", "Sign=WXPay");
		payParamsJSON.put("sign", sign);
		order.put("wxPayConfig", payParamsJSON);

		if (StringUtils.isNotBlank(prepay_id)) {
			log.info("微信支付预下单成功,Params=" + paramsMap);
		} else {
			log.error("微信支付预下单失败,Params=" + paramsMap);
			throw new BizHandleException("操作失败,微信支付异常!");
		}
	}

	/**
	 * 订单支付宝支付加签
	 * 
	 * @param order
	 * @param subject
	 * @param body
	 */
	private void alipaySign(Order order, String subject, String body) throws BizHandleException {

		StringBuilder orderInfo = new StringBuilder();
		orderInfo.append("partner=\"").append(PropertiesContent.get(Const.ALIPAY_PID_CFG)).append("\"");
		orderInfo.append("&seller_id=\"").append(PropertiesContent.get(Const.ALIPAY_SELLER_ID_CFG)).append("\"");
		orderInfo.append("&out_trade_no=\"").append(order.getStr("orderId")).append("\"");
		orderInfo.append("&subject=\"").append(subject).append("\"");
		orderInfo.append("&body=\"").append(body).append("\"");
		orderInfo.append("&total_fee=\"")
				.append(String.valueOf(
						order.getBigDecimal("payment").divide(new BigDecimal(100L), 2, RoundingMode.HALF_EVEN)))
				.append("\"");
		orderInfo.append("&notify_url=\"").append(PropertiesContent.get(Const.ALIPAY_NOTIFY_URL_CFG)).append("\"");
		orderInfo.append("&service=\"").append("mobile.securitypay.pay").append("\"");
		orderInfo.append("&payment_type=\"").append("1").append("\"");
		orderInfo.append("&_input_charset=\"").append(PropertiesContent.get(Const.ALIPAY_MSG_CHARSET_CFG)).append("\"");
		orderInfo.append("&it_b_pay=\"").append("1c").append("\"");

		String sign = null;
		try {
			sign = AlipaySignature.rsaSign(orderInfo.toString(), PropertiesContent.get(Const.MT_PRIVATE_KEY_CFG),
					PropertiesContent.get(Const.ALIPAY_MSG_CHARSET_CFG));
			sign = URLEncoder.encode(sign, PropertiesContent.get(Const.ALIPAY_MSG_CHARSET_CFG));
		} catch (Exception e) {
			log.error("生成订单支付签名异常", e);
			throw new BizHandleException("生成订单支付签名异常", e);
		}

		orderInfo.append("&sign_type=\"RSA\"&sign=\"" + sign + "\"");
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderInfo", orderInfo.toString());
		order.put("alipayConfig", params);
	}
	// 商家订单查询
	public void getOrder() {
		int shopId = ((SessionModel) this.getSessionAttr("SessionModel"))
				.getShopId();
		Map<String, Object> map = getParas();
		map.put("shopid", shopId + "");
		List<Record> list = Db
				.find("select mto.orderId,mtt.themename,mtu.username,mto.money,mto.payment,case when mto.status=0 then '等待支付' when mto.status=1 then '已支付' when mto.status=2 then '已退款' else '已完成' end status,mto.createTime "
						+ getSql("order.order", map));
		this.renderJson((new JsonUtil(list)).toString());
	}
}
